package com.ddstation.app.doctor_verify.controller;

import com.ddstation.app.doctor_verify.mapper.AppDoctorVerifyMapper;
import com.ddstation.app.doctor_verify.service.AppDoctorVerifyService;
import com.ddstation.common.access_token.service.AccessTokenService;
import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.common.util.CheckUtil;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.doctor.entity.DdDoctorEntity;
import com.ddstation.doctor.service.DdDoctorServiceItf;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.master.utils.DataDictionaryCons;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AppDoctorVerifyController {

    @Inject private DataDictionaryService dataDictionaryService;
    @Inject private AppDoctorVerifyService appDoctorVerifyService;
    @Inject private AccessTokenService accessTokenService;
    @Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
    @Inject private AppDoctorVerifyMapper appDoctorVerifyMapper;
    @Inject private DdDoctorServiceItf ddDoctorService;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 资质备案
     * @param params
     * @return
     */
    @RequestMapping(value="appinvs_doctor_verify.do/load", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> invsDoctorVerifyLoadEvent(
            @RequestBody Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("errCode", -1);
        if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
                || CheckUtil.isEmpty(params.get("doctorId"))) {
            return retMap;
        }
        // 诊疗范围
        List<MaDataDictionaryEntity> scopePracticeList = dataDictionaryService.getCodeList(DataDictionaryCons.CODE_SCOPE_PRACTICE);
        // 科室
//        List<MaDataDictionaryEntity> technicalOfficesList = dataDictionaryService.getCodeList(DataDictionaryCons.CODE_TECHNICAL_OFFICES);
        // 职称
        List<MaDataDictionaryEntity> technicalTitleList = dataDictionaryService.getCodeList(DataDictionaryCons.CODE_TECHNICAL_TITLE);
        retMap.put("scopePracticeList", scopePracticeList);
//        retMap.put("technicalOfficesList", technicalOfficesList);
        retMap.put("technicalTitleList", technicalTitleList);
        retMap.put("errCode", 0);
        retMap.put("errorMsg", "");
        return retMap;
    }

    /**
     * 身份证上传进行人脸认证
     * @param params
     * @return
     */
    @RequestMapping(value="appinvs_doctor_verify.do/faceUpload", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> invsDoctorVerifyFaceUploadEvent(
            @RequestBody Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("errCode", -1);
        if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
                || CheckUtil.isEmpty(params.get("doctorId"))
                || CheckUtil.isEmpty(params.get("baseImg1"))
                || CheckUtil.isEmpty(params.get("baseImg2"))
                || CheckUtil.isEmpty(params.get("baseImg3"))) {
            return retMap;
        }

        String institutionId = params.get("institutionId").toString();
        Integer doctorId = Integer.parseInt(params.get("doctorId").toString());
        String name = params.get("name").toString();
        String idCard = params.get("idCard").toString();
        String baseImg1 = params.get("baseImg1").toString();    //身份证正面
        String baseImg2 = params.get("baseImg2").toString();    //身份证反面
        String baseImg3 = params.get("baseImg3").toString();    //人脸采集照片

        retMap.putAll(appDoctorVerifyService.doVerify(institutionId,doctorId,baseImg1,baseImg2,baseImg3, name, idCard));
        return retMap;
    }

    /**
     * 资料保存
     * @param params
     * @return
     */
    @RequestMapping(value="appinvs_doctor_verify.do/save", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> invsDoctorVerifySaveEvent(
            @RequestBody Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("errCode", -1);
        if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
                || CheckUtil.isEmpty(params.get("doctorId"))
                || CheckUtil.isEmpty(params.get("token"))
                || CheckUtil.isEmpty(params.get("name"))
                || CheckUtil.isEmpty(params.get("idCard"))
                || CheckUtil.isEmpty(params.get("scopePracticeCode"))
//                || CheckUtil.isEmpty(params.get("technicalOfficesCode"))
                || CheckUtil.isEmpty(params.get("technicalTitleCode"))
                || CheckUtil.isEmpty(params.get("idCardImageIds"))
                ) {
            if (!"10".equals(params.get("technicalTitleCode"))) {
                if(CheckUtil.isEmpty(params.get("qualification"))
                        || CheckUtil.isEmpty(params.get("doctorLicence"))
                        || CheckUtil.isEmpty(params.get("qualificationIds"))
                        || CheckUtil.isEmpty(params.get("doctorLicenceIds"))) {
                    return retMap;
                }
            }
        }
        String institutionId = params.get("institutionId").toString();
        String doctorId = params.get("doctorId").toString();
        String token = params.get("token").toString();
        String name = params.get("name").toString();
        String idCard = params.get("idCard").toString();
        String qualification = null == params.get("qualification")? null : params.get("qualification").toString();
        String doctorLicence = null == params.get("doctorLicence") ? null : params.get("doctorLicence").toString();
        String scopePracticeCode = params.get("scopePracticeCode").toString();
//        String technicalOfficesCode = params.get("technicalOfficesCode").toString();
        String technicalTitleCode = params.get("technicalTitleCode").toString();
        String idCardImageIds = params.get("idCardImageIds").toString();
        String qualificationIds = null == params.get("qualificationIds") ? null : params.get("qualificationIds").toString();
        String doctorLicenceIds = null == params.get("doctorLicenceIds") ? null : params.get("doctorLicenceIds").toString();
        DdDoctorEntity entity = new DdDoctorEntity();
        entity.setId(doctorId);
        entity.setName(name);
        entity.setIdCard(idCard);
        entity.setQualification(qualification);
        entity.setDoctorLicence(doctorLicence);
        entity.setScopePractice(scopePracticeCode);
        entity.setScopePractice(scopePracticeCode);
//        entity.setTechnicalOffices(technicalOfficesCode);
        entity.setTechnicalTitle(technicalTitleCode);
        entity.setIdCardAtta(idCardImageIds);
        entity.setQualificationAtta(qualificationIds);
        entity.setDoctorLicenceAtta(doctorLicenceIds);
        entity.setDoctorVerifySt(20);
        if (appDoctorVerifyService.updateDoctorInfo(entity,institutionId) == 1) {
            appDoctorVerifyService.updateStatus(token);
            retMap.put("errCode", 0);
        } else {
            retMap.put("errorMsg", "更新失败，请重新提交");
        }
        return retMap;
    }


    /**
     * 人脸认证登录
     * @param params
     * @return
     */
    @RequestMapping(value="appinvs_doctor_verify.do/faceLogin", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> invsDoctorVerifyFaceLoginEvent(
            @RequestBody Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("errCode", -1);
        if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
                || CheckUtil.isEmpty(params.get("doctorId"))
                || CheckUtil.isEmpty(params.get("token"))
                || CheckUtil.isEmpty(params.get("baseImg"))) {
            return retMap;
        }

        String institutionId = params.get("institutionId").toString();
        Integer doctorId = Integer.parseInt(params.get("doctorId").toString());
        String token = params.get("token").toString();
        String baseImg = params.get("baseImg").toString();    //人脸采集照片

        retMap.putAll(appDoctorVerifyService.doVerifyLogin(institutionId,doctorId,token,baseImg));
        return retMap;
    }

    /**
     * 扫码登录（是否需要人脸识别）
     * @param params
     * @return
     */
    @RequestMapping(value="appinvs_doctor_verify.do/check", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> invsDoctorVerifyFaceLoginFlagEvent(
            @RequestBody Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("errCode", -1);
        if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
                || CheckUtil.isEmpty(params.get("doctorId"))
                || CheckUtil.isEmpty(params.get("token"))
                || CheckUtil.isEmpty(params.get("shortAccessToken"))) {
            return retMap;
        }

        String institutionId = params.get("institutionId").toString();
        String doctorId = params.get("doctorId").toString();
        String token = params.get("token").toString();
        String sToken = params.get("shortAccessToken").toString();

        String errmsg = "";
        if (!accessTokenService.validateShortToken(sToken)) {
            errmsg ="token无效，请重新登录";
        } else {
            String[] t = sToken.split("-");
            if (t == null || t.length < 3) {
                errmsg = "token不合法：token格式不正常";
            } else {
                if (StringUtils.isNotBlank(institutionId) && !institutionId.equals(t[0])) {
                    errmsg = "token不合法：institutionId和token中的值不一致";
                }
                if (StringUtils.isNotBlank(doctorId) && !doctorId.equals(t[1])) {
                    errmsg = "token不合法：doctorId和token中的值不一致";
                }
            }
        }
        if ("".equals(errmsg)) {
            DtHealthManageInstitutionEntity institution = dtHealthManageInstitutionMapper.select(institutionId);
            // 是否属于卫监监管
            retMap.put("face", institution.getUnderInvs());
            if (institution.getUnderInvs() == 1) {
                DdDoctorEntity entity = ddDoctorService.getDoctorInfo(doctorId);
                if (entity.getDoctorVerifySt() != 20) {
                    retMap.put("errorMsg", "医生未认证，请先认证");
                    return retMap;
                }
            }
            if (appDoctorVerifyService.updateLogByToken(token,Integer.parseInt(doctorId),institutionId) > 0) {
                retMap.put("errCode", 0);
            } else {
                retMap.put("errorMsg", "登录失败，请重新提交");
            }
        } else {
            retMap.put("errorMsg", errmsg);
        }

//        retMap.putAll(appDoctorVerifyService.doVerifyLogin(institutionId,doctorId,token,baseImg));
        return retMap;
    }

    /**
     * 扫码登录
     * @param params
     * @return
     */
    @RequestMapping(value="appinvs_doctor_verify.do/confirmLogin", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> invsDoctorQrcodeConfirmLoginEvent(
            @RequestBody Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("errCode", -1);
        if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
                || CheckUtil.isEmpty(params.get("doctorId"))
                || CheckUtil.isEmpty(params.get("token"))) {
            return retMap;
        }

//        String institutionId = params.get("institutionId").toString();
//        Integer doctorId = Integer.parseInt(params.get("doctorId").toString());
        String token = params.get("token").toString();
        if (appDoctorVerifyMapper.updateLogId(token, System.currentTimeMillis()) == 1) {
            retMap.put("errCode", 0);
        } else {
            retMap.put("errorMsg", "系统繁忙，请稍后再试");
        }

        return retMap;
    }
}
